/*
 * Copyright 2025 arisgo@163.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.arisgo.cloud.web.mybatis.interceptor;

import com.arisgo.cloud.common.utils.ReflectUtil;
import com.arisgo.cloud.web.mybatis.config.ArisgoMybatisProperties;
import com.arisgo.cloud.web.utils.RequestUtil;
import com.google.common.collect.Lists;
import lombok.AllArgsConstructor;
import org.apache.ibatis.binding.MapperMethod;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Signature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Optional;
import java.util.Properties;

/**
 * 字段填充拦截器
 * 默认填充字段 创建人 创建时间 更新人 更新时间
 * 可以自定义字段，如果设置自定义字段，则默认配置失效
 * 不支持单表设置
 *
 * @author Arisgo
 * @since 2024/1/19
 */
@Component
@AllArgsConstructor
@Intercepts({@Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class})})
public class MybatisInterceptor implements Interceptor {

    private static final Logger logger = LoggerFactory.getLogger(MybatisInterceptor.class);

    private final ArisgoMybatisProperties arisgoMybatisProperties;

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        MappedStatement statement = (MappedStatement) invocation.getArgs()[0];
        SqlCommandType type = statement.getSqlCommandType();
        Object arg = invocation.getArgs()[1];
        if (!(arg instanceof MapperMethod.ParamMap<?> parameter)) {
            return invocation.proceed();
        }

        // 获取填充对象
        List<Object> entities = new ArrayList<>();
        if (parameter.containsKey("$$entity")) {
            entities.add(parameter.get("$$entity"));
        } else if (parameter.containsKey("$$entities")) {
            Object object = parameter.get("$$entities");
            if (object instanceof Collection<?> collection) {
                entities = Lists.newArrayList(collection);
            }
        }
        // 设置默认值
        autoFillValue(entities, type);

        return invocation.proceed();
    }

    private void autoFillValue(List<Object> entities, SqlCommandType type) throws IllegalAccessException {
        // 获取需要自动填充字段
        List<ArisgoMybatisProperties.FieldValue> configs = arisgoMybatisProperties.getColumns().stream().filter(f -> f.getCommands().contains(type.name())).toList();
        if (CollectionUtils.isEmpty(configs) || CollectionUtils.isEmpty(entities)) {
            return;
        }
        String[] fieldNames = configs.stream().map(ArisgoMybatisProperties.FieldValue::getField).distinct().toArray(String[]::new);
        List<Field> fields = ReflectUtil.getFields(entities.get(0).getClass(), fieldNames);

        // 设置默认值
        for (Field field : fields) {
            Optional<ArisgoMybatisProperties.FieldValue> optional = configs.stream().filter(f -> f.getField().equals(field.getName())).findFirst();
            if (optional.isEmpty()) {
                continue;
            }
            try {
                // insert操作，为null更新；update操作，覆盖更新
                Object value = getDefaultValue(field, optional.get().getValue());
                if (null != value) {
                    field.setAccessible(true);
                    for (Object entity : entities) {
                        if (null == field.get(entity) || "UPDATE".equals(type.name())) {
                            field.set(entity, value);
                        }
                    }
                    field.setAccessible(false);
                }
            } catch (IllegalArgumentException e) {
                logger.warn(e.getMessage());
            }
        }
    }

    @Override
    public Object plugin(Object target) {
        return Interceptor.super.plugin(target);
    }

    @Override
    public void setProperties(Properties properties) {
        Interceptor.super.setProperties(properties);
    }

    private Object getDefaultValue(Field field, Object value) {
        if (null == value) {
            return null;
        }
        if (value instanceof String val) {
            if (0 == val.indexOf("$")) {
                Object userInfo = RequestUtil.getUserInfo();
                if (null == userInfo) {
                    return null;
                }
                Field property = ReflectUtil.getField(userInfo, val.substring(1));
                if (null == property) {
                    return null;
                }
                try {
                    property.setAccessible(true);
                    return property.get(userInfo);
                } catch (IllegalAccessException e) {
                    logger.warn(e.getMessage());
                } finally {
                    property.setAccessible(false);
                }
                return null;
            } else if ("current_time".equalsIgnoreCase(val)) {
                // 特殊字符 currentTime 表示获取当前时间
                Class<?> type = field.getType();
                if (type.isAssignableFrom(Date.class)) {
                    return new Date();
                } else if (type.isAssignableFrom(LocalDate.class)) {
                    return LocalDate.now();
                } else if (type.isAssignableFrom(LocalDateTime.class)) {
                    return LocalDateTime.now();
                }
            }
        } else if (value instanceof Number val) {
            // 有小数部分，转BigDecimal
            if (val.toString().matches("^\\d+(\\.\\d+)?$")) {
                return new BigDecimal(val.toString());
            }
        }
        return value;
    }

}
